package controllers

import (
	"baokaobang/datasourse"
	"baokaobang/models"
	"baokaobang/utils"
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/sessions"
	"strings"
	"time"
)

type MajorProbability struct {
	Ctx iris.Context
}

// 获取某个学生专业录取概率列表
func (c *MajorProbability) PostList() interface{} {
	channel := c.Ctx.PostValueDefault("channel", "")
	collegeId := c.Ctx.PostValueDefault("collegeId", "")

	if len(channel) <= 0 {
		return utils.CommonRes(1000, "请提供渠道", "")
	}
	if len(collegeId) <= 0 {
		return utils.CommonRes(1000, "请提供院校id", "")
	}

	var userId int64
	if strings.EqualFold(channel, "wechat") {
		token := c.Ctx.GetHeader("token")
		claims, err := utils.ParseToken(token)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("解析token出错：%s", err.Error()), "")
		}
		userId = utils.Atoi64(claims.Id)
	} else {
		session := sessions.Get(c.Ctx)
		userId, _ = session.GetInt64(fmt.Sprintf("%sUserId", channel))
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	year := time.Now().Format("2006")

	majorProbabilityList := make([]models.StudentMajorProbabilityObj, 0)
	err = db.Table(new(models.StudentMajorProbability)).Alias("smp").
		Join("INNER", []string{"enrollment_plan", "ep"}, "smp.enrollment_plan_id = ep.id").
		Where("smp.user_id = ? and smp.college_id = ? and smp.year = ?", userId, collegeId, year).Find(&majorProbabilityList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取专业概率列表：%s", err.Error()), "")
	}

	return utils.CommonRes(20000, "成功获取专业概率列表", majorProbabilityList)
}